Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.

In [1]:
visualize = True # toggle whether or not to visualize example images

Step 0: Load The Data

In [2]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = '../train.p'
validation_file= '../valid.p'
testing_file = '../test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
print("Loaded {} training, {} validation and {} test images.".format(len(X_train), len(X_valid), len(X_test)))
Loaded 34799 training, 4410 validation and 12630 test images.

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [3]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results
import pandas as pd
import random
import numpy as np

# TODO: Number of training examples
n_train = len(X_train)

# TODO: Number of validation examples
n_validation = len(X_valid)

# TODO: Number of testing examples.
n_test = len(X_test)

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?

In [4]:
# Function for mapping numeric labels to the strings describing a sign
import csv
signs = {}
with open('signnames.csv', 'r') as names:
    reader = csv.reader(names, delimiter=',')
    next(reader) # skip the header
    for row in reader:
        signs[int(row[0])] = row[1]

def sign_name(key):
    return signs[int(key)]
In [5]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
plt.rcParams['figure.figsize'] = [15, 15]
import math

def show_single_image(idx, image=None):
    plt.title(sign_name(y_train[idx]))
    if image is not None:
        plt.imshow(image)
    else:
        plt.imshow(X_train[idx])
        
def show_images(idxs, images=X_train, labels=y_train, title=None, max_cols=5):
    fig = plt.figure()
    fig.clf()
    
    n_images = len(idxs)
    rows = math.ceil(math.sqrt(n_images))
    cols = rows
    
    if cols >= max_cols:
        cols = max_cols
        rows = math.ceil(n_images/max_cols)
        fig_size = fig.get_size_inches()[0]
        enlarge_by = rows/cols
        fig.set_size_inches(fig_size,fig_size*enlarge_by)
    
    if title:
        print("Showing {} Images from {}:".format(n_images, title))
    def subplot(title, image, idx):
        p = fig.add_subplot(rows, cols, idx + 1, xmargin=0.52)
        p.set_title(title)
        plt.imshow(image)
        plt.axis('off') # don't show numbered axes
        
    for i, idx in enumerate(idxs):
        subplot(sign_name(labels[idx]), images[idx], i)
    fig.tight_layout()
In [6]:
# Show the distribution of images over the classes
def plot_distribution_of_classes(labels, dataset_name='unknown'):
    instance_count = []
    for class_idx in range(n_classes):
        instance_count.append(len(np.where(labels==class_idx)[0]))

    n_instances = len(instance_count)
    fig = plt.figure()
    fig.set_size_inches(15, 10) # use a non-square size
    plt.ylim([-1, n_instances]) # set proper limits (reducing whitespace on top and bottom)
    ax = fig.add_subplot(111)
    ax.set_title("Distribution of examples for each class in the {} dataset".format(dataset_name))
    labels = list(signs.values())[0:n_instances]
    # plot a horizontal bar chart in reverse order, so as to get the index zero at the top
    ax.barh([x for x in range(n_instances)][::-1], instance_count, tick_label=labels, align='center')
    fig.tight_layout()

Training Dataset Distribution

In [7]:
if visualize:
    plot_distribution_of_classes(y_train, 'training')

Validation Dataset Distribution

In [8]:
if visualize:
    plot_distribution_of_classes(y_valid, 'validation')

Test Dataset Distribution

In [9]:
if visualize:
    plot_distribution_of_classes(y_test, 'test')
In [10]:
# Find some images from each of the classes
import random
def get_examples_from_all_classes(labels):
    examples_from_all_classes = []
    random.seed(42)
    for class_idx in range(n_classes):
        occ = np.where(labels == class_idx)[0]
        examples_from_all_classes.append(random.choice(occ))
    return examples_from_all_classes

if visualize:
    examples_from_all_classes = get_examples_from_all_classes(y_train)

Example Images from Training Set Classes

In [11]:
if visualize:
    show_images(examples_from_all_classes, title='classes of the training set', max_cols=5)
Showing 43 Images from classes of the training set:

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [12]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import os, time
import skimage.exposure as exp

# normalize images
def normalize(image_list):
    normalized_images = []# np.empty_like(image_list)
    for idx in range(len(image_list)):
        assert image_list[idx].dtype == np.uint8
        #normalized_images.append((image_list[idx] - 128.) / 128.)
        normalized_images.append(exp.equalize_hist(image_list[idx]) - 0.5)
    return np.array(normalized_images)

def statistics(image_list, dataset_name):
    print("Statistics on '{}':".format(dataset_name))
    print("  mean: {:.4f}, std dev: {:.4f}".format(image_list.mean(), image_list.std()))


def transform_or_load(data, caption, filename, func=normalize):
    if not os.path.isfile(filename):
        print("Transforming '{}'...".format(caption))
        t1 = time.time()
        normalized_data = func(data)
        print("  took {:.3f}s".format(time.time()-t1))
        with open(filename, mode='wb') as f:
            pickle.dump(normalized_data, f)
        print("Wrote {} records to {}.".format(len(normalized_data), filename))
    else:
        print("Loading '{}' from file {}...".format(caption, filename))
        t1 = time.time()
        with open(filename, mode='rb') as f:
            normalized_data = pickle.load(f)
        print("  read {} records in {:.3f}s".format(len(normalized_data), time.time()-t1))
    statistics(normalized_data, caption)
    return normalized_data

X_train_norm = transform_or_load(X_train, "training data", "train_norm.p", func=normalize)
X_test_norm = transform_or_load(X_test, "testing data", "test_norm.p", func=normalize)
X_valid_norm = transform_or_load(X_valid, "validation data", "valid_norm.p", func=normalize)
Loading 'training data' from file train_norm.p...
  read 34799 records in 1.361s
Statistics on 'training data':
  mean: 0.0122, std dev: 0.2911
Loading 'testing data' from file test_norm.p...
  read 12630 records in 0.449s
Statistics on 'testing data':
  mean: 0.0138, std dev: 0.2928
Loading 'validation data' from file valid_norm.p...
  read 4410 records in 0.155s
Statistics on 'validation data':
  mean: 0.0129, std dev: 0.2918

Image augmentation (geometrical + noise)

In [13]:
n_sets_augment = 2  # create two sets of augmented images

from skimage import transform as skitf
from skimage import util as skiutil
from skimage import exposure as skiexp


import numpy as np
def augment_image(img):
    scale = random.uniform(0.9, 1.3)
    max_angle = 10
    rotation = random.uniform(-max_angle/180.*math.pi, max_angle/180.*math.pi)
    to_center = 16*scale - 16
    trafo = skitf.AffineTransform(scale=(scale, scale), rotation=0,
                              translation=(-to_center, -to_center))
    scaled = skitf.warp(img, trafo)
    rotated = skitf.rotate(scaled, random.randint(-max_angle, max_angle))
    noisy = skiutil.random_noise(rotated, var=0.001)
    return exp.equalize_hist(noisy) - 0.5


def augment_images(image_list):
    images = []
    for image in image_list:
        images.append(augment_image(image))
    return np.array(images)

augmented_images = []
for i in range(n_sets_augment):
    augmented_images.append(transform_or_load(X_train_norm, \
        "augmented training data", "train_augmented_{}.p".format(i), func=augment_images))
Loading 'augmented training data' from file train_augmented_0.p...
  read 34799 records in 1.344s
Statistics on 'augmented training data':
  mean: 0.0456, std dev: 0.2353
Loading 'augmented training data' from file train_augmented_1.p...
  read 34799 records in 0.250s
Statistics on 'augmented training data':
  mean: 0.0458, std dev: 0.2352
In [14]:
all_augmented = np.concatenate(augmented_images)
In [15]:
print("number of augmented images:", len(all_augmented))
number of augmented images: 69598

Normalized Augmented Images

In [16]:
if visualize: # reverse subtraction of 0.5 below for prettier looking images
    show_images(examples_from_all_classes[0:16], \
                images=augmented_images[0]+0.5, \
                title='classes of the training set', max_cols=5)
Showing 16 Images from classes of the training set:
In [17]:
# Create the final training datasets 
X_train_final = np.append(X_train_norm, all_augmented, axis=0)
y_train_final = np.append(np.append(y_train, y_train), y_train)
assert len(X_train_final) == len(y_train_final)

X_valid_final = X_valid_norm
y_valid_final = y_valid
assert len(X_valid_final) == len(y_valid_final)

Model Architecture

In [18]:
### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf
from tensorflow.contrib.layers import flatten

class LeNet(object):
    def init_bias(self, size):
        return tf.Variable(tf.zeros(size))
    
    def init_weights(self, size):
        return tf.Variable(tf.truncated_normal(size, self.mu, self.sigma))
    
    def __init__(self, x, dropout):
        self.mu = 0
        self.sigma = 0.1
        image_depth = 3
        c1_depth = 6*4
        c2_depth = 16*4
        f1_width = 240
        f2_width = 160
        full_stride = [1, 1, 1, 1]
        half_stride = [1, 2, 2, 1]
        weights = {
            'c1': self.init_weights([5, 5, image_depth, c1_depth]),
            'c2': self.init_weights([5,5,c1_depth,c2_depth]),
            'f1': self.init_weights([5*5*c2_depth, f1_width]),
            'f2': self.init_weights([f1_width, f2_width]),
            'f3': self.init_weights([f2_width, n_classes])
        }
        biases = {
            'c1': self.init_bias(c1_depth),
            'c2': self.init_bias(c2_depth),
            'f1': self.init_bias(f1_width),
            'f2': self.init_bias(f2_width),
            'f3': self.init_bias(n_classes)
        }
        
        self.layers = dict()
        
        # conv1, input = 32x32x3, output = 28x28x6
        self.layers["conv1"] = tf.nn.conv2d(x, weights['c1'], strides=full_stride, padding='VALID') 
        self.layers["conv1"] = tf.nn.bias_add(self.layers["conv1"], biases['c1'])
        self.layers["conv1"] = tf.nn.relu(self.layers["conv1"], name="conv1")
        print("conv1", self.layers["conv1"].get_shape())
        
        # pooling, input = 28x28x6, output=14x14x6
        self.layers["pool1"] = tf.nn.max_pool(self.layers["conv1"], ksize=half_stride, strides=half_stride, padding='VALID', name="pool1")
        print("pool1", self.layers["pool1"].get_shape())


        self.layers["conv2"] = tf.nn.conv2d(self.layers["pool1"], weights['c2'], strides=full_stride, padding='VALID') #+ biases['c2']
        self.layers["conv2"] = tf.nn.bias_add(self.layers["conv2"], biases['c2'])
        self.layers["conv2"] = tf.nn.relu(self.layers["conv2"], name="conv2")
        print("conv2", self.layers["conv2"].get_shape())


        # pooling, input = 10x10x16, output = 5x5x16
        self.layers["pool2"] = tf.nn.max_pool(self.layers["conv2"], ksize=half_stride, strides=half_stride, padding='VALID', name="pool2")
        print("pool2", self.layers["pool2"].get_shape())


        self.layers["flattened"] = flatten(self.layers["pool2"])
        print("flattened", self.layers["flattened"].get_shape())


        self.layers["f1"] = tf.matmul(self.layers["flattened"], weights['f1']) + biases['f1']
        self.layers["f1"] = tf.nn.relu(self.layers["f1"])
        self.layers["f1"] = tf.nn.dropout(self.layers["f1"], dropout, name="f1")
        print("f1", self.layers["f1"].get_shape())

        self.layers["f2"] = tf.matmul(self.layers["f1"], weights['f2']) + biases['f2']
        self.layers["f2"] = tf.nn.relu(self.layers["f2"])
        self.layers["f2"] = tf.nn.dropout(self.layers["f2"], dropout, name="f2")
        print("f2", self.layers["f2"].get_shape())


        self.layers["f3"] = tf.matmul(self.layers["f2"], weights['f3']) + biases['f3']
        print("f3", self.layers["f3"].get_shape())

        self.logits = self.layers["f3"]
        
    

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [19]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
x = tf.placeholder(tf.float32, (None, image_shape[0], image_shape[1], image_shape[2]))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)
keep_prob = tf.placeholder(tf.float32)
In [20]:
rate = 0.001
dropout = 0.75
lenet = LeNet(x, dropout)
logits = lenet.logits

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate=rate)
training_operation = optimizer.minimize(loss_operation)
conv1 (?, 28, 28, 24)
pool1 (?, 14, 14, 24)
conv2 (?, 10, 10, 64)
pool2 (?, 5, 5, 64)
flattened (?, 1600)
f1 (?, 240)
f2 (?, 160)
f3 (?, 43)
In [21]:
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples

def evaluate_print(X_data, y_data):
    print("Predicting {} signs:".format(len(X_data)))
    sess = tf.get_default_session()
    total_accuracy = 0
    for idx in range(len(X_data)):
        feed_dict = {x: np.array([X_data[idx]]), y: np.array([y_data[idx]]), keep_prob: 1.}
        accuracy = sess.run(accuracy_operation, feed_dict=feed_dict)
        prediction = sess.run(tf.argmax(logits, 1), feed_dict=feed_dict)
        actual = sess.run(tf.argmax(one_hot_y, 1), feed_dict=feed_dict)
        if accuracy == 1:
            print("  Correctly predicted '{}' (index {})".format(sign_name(int(prediction)), prediction))
        else:
            print("  Error: predicted '{}' but was '{}' (indices {}/{})".format(\
                sign_name(int(prediction)), sign_name(int(actual)), prediction, actual))
        total_accuracy += accuracy
    return total_accuracy / len(X_data)
In [22]:
from sklearn.utils import shuffle
from IPython import display

EPOCHS = 50
BATCH_SIZE = 128

print_dot = math.ceil(len(X_train_final)/BATCH_SIZE/80) * BATCH_SIZE

train_accs = [0]
accuracies = [0]

import time
t1 = time.time()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train_final)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train_final, y_train_final = shuffle(X_train_final, y_train_final)
        for offset in range(0, num_examples, BATCH_SIZE):
            if offset % print_dot == 0:
                print('.', end='', flush=True)
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train_final[offset:end], y_train_final[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
            
        validation_accuracy = evaluate(X_valid_final, y_valid_final)
        train_accuracy = evaluate(X_train_final, y_train_final)
        print("\nEpoch {} Training Accuracy = {:.5f}".format(i+1, train_accuracy))
        print("Validation Accuracy = {:.5f}".format(validation_accuracy))
        train_accs.append(train_accuracy)
        accuracies.append(validation_accuracy)


    saver.save(sess, './lenet')
    print("Model saved")
    
t2 = time.time()
print("This training took {:.2f}s".format(t2-t1))
Training...

...........................................................................
Epoch 1 Training Accuracy = 0.89744
Validation Accuracy = 0.91746
...........................................................................
Epoch 2 Training Accuracy = 0.93803
Validation Accuracy = 0.94104
...........................................................................
Epoch 3 Training Accuracy = 0.95396
Validation Accuracy = 0.94898
...........................................................................
Epoch 4 Training Accuracy = 0.96416
Validation Accuracy = 0.95125
...........................................................................
Epoch 5 Training Accuracy = 0.96987
Validation Accuracy = 0.95941
...........................................................................
Epoch 6 Training Accuracy = 0.97457
Validation Accuracy = 0.96145
...........................................................................
Epoch 7 Training Accuracy = 0.97527
Validation Accuracy = 0.95488
...........................................................................
Epoch 8 Training Accuracy = 0.97932
Validation Accuracy = 0.96871
...........................................................................
Epoch 9 Training Accuracy = 0.98311
Validation Accuracy = 0.96417
...........................................................................
Epoch 10 Training Accuracy = 0.98304
Validation Accuracy = 0.96054
...........................................................................
Epoch 11 Training Accuracy = 0.98337
Validation Accuracy = 0.95646
...........................................................................
Epoch 12 Training Accuracy = 0.98321
Validation Accuracy = 0.95488
...........................................................................
Epoch 13 Training Accuracy = 0.98657
Validation Accuracy = 0.96122
...........................................................................
Epoch 14 Training Accuracy = 0.98589
Validation Accuracy = 0.96644
...........................................................................
Epoch 15 Training Accuracy = 0.98702
Validation Accuracy = 0.96327
...........................................................................
Epoch 16 Training Accuracy = 0.99004
Validation Accuracy = 0.96327
...........................................................................
Epoch 17 Training Accuracy = 0.98813
Validation Accuracy = 0.96531
...........................................................................
Epoch 18 Training Accuracy = 0.99003
Validation Accuracy = 0.96190
...........................................................................
Epoch 19 Training Accuracy = 0.98958
Validation Accuracy = 0.96304
...........................................................................
Epoch 20 Training Accuracy = 0.98933
Validation Accuracy = 0.96621
...........................................................................
Epoch 21 Training Accuracy = 0.99111
Validation Accuracy = 0.96304
...........................................................................
Epoch 22 Training Accuracy = 0.99091
Validation Accuracy = 0.96259
...........................................................................
Epoch 23 Training Accuracy = 0.99052
Validation Accuracy = 0.96553
...........................................................................
Epoch 24 Training Accuracy = 0.99195
Validation Accuracy = 0.96440
...........................................................................
Epoch 25 Training Accuracy = 0.99329
Validation Accuracy = 0.96508
...........................................................................
Epoch 26 Training Accuracy = 0.99336
Validation Accuracy = 0.96463
...........................................................................
Epoch 27 Training Accuracy = 0.99060
Validation Accuracy = 0.95941
...........................................................................
Epoch 28 Training Accuracy = 0.99228
Validation Accuracy = 0.96190
...........................................................................
Epoch 29 Training Accuracy = 0.99336
Validation Accuracy = 0.96553
...........................................................................
Epoch 30 Training Accuracy = 0.99241
Validation Accuracy = 0.96825
...........................................................................
Epoch 31 Training Accuracy = 0.99459
Validation Accuracy = 0.96689
...........................................................................
Epoch 32 Training Accuracy = 0.99115
Validation Accuracy = 0.96349
...........................................................................
Epoch 33 Training Accuracy = 0.99146
Validation Accuracy = 0.96395
...........................................................................
Epoch 34 Training Accuracy = 0.99359
Validation Accuracy = 0.96871
...........................................................................
Epoch 35 Training Accuracy = 0.99317
Validation Accuracy = 0.97120
...........................................................................
Epoch 36 Training Accuracy = 0.99426
Validation Accuracy = 0.96553
...........................................................................
Epoch 37 Training Accuracy = 0.99531
Validation Accuracy = 0.97120
...........................................................................
Epoch 38 Training Accuracy = 0.99254
Validation Accuracy = 0.96757
...........................................................................
Epoch 39 Training Accuracy = 0.99309
Validation Accuracy = 0.96077
...........................................................................
Epoch 40 Training Accuracy = 0.99390
Validation Accuracy = 0.96576
...........................................................................
Epoch 41 Training Accuracy = 0.99546
Validation Accuracy = 0.96531
...........................................................................
Epoch 42 Training Accuracy = 0.99420
Validation Accuracy = 0.97098
...........................................................................
Epoch 43 Training Accuracy = 0.99385
Validation Accuracy = 0.96871
...........................................................................
Epoch 44 Training Accuracy = 0.99515
Validation Accuracy = 0.96780
...........................................................................
Epoch 45 Training Accuracy = 0.99441
Validation Accuracy = 0.96417
...........................................................................
Epoch 46 Training Accuracy = 0.99110
Validation Accuracy = 0.96372
...........................................................................
Epoch 47 Training Accuracy = 0.98962
Validation Accuracy = 0.95397
...........................................................................
Epoch 48 Training Accuracy = 0.99570
Validation Accuracy = 0.97052
...........................................................................
Epoch 49 Training Accuracy = 0.99372
Validation Accuracy = 0.96463
...........................................................................
Epoch 50 Training Accuracy = 0.99247
Validation Accuracy = 0.96576
Model saved
This training took 840.97s

Training Progress

In [23]:
fig = plt.figure()
fig.set_size_inches(15, 5)
fig.suptitle('Validation and Training Accuracies')
plt.plot(accuracies, label='validation accuracy')
plt.plot(train_accs, label='training accuracy')
plt.gca().set_xlim([0, EPOCHS])
plt.gca().set_ylim([0.8, 1.0])
plt.gca().set_yticks(np.arange(0.8, 1.0, 0.02))
plt.xlabel("epochs")
plt.ylabel("accuracy")
plt.grid()
plt.axhline(0.93, ls='--', color='r', label='target 0.93')
plt.legend(loc='lower right')
print("last accuracy: {}".format(accuracies[-1]))
last accuracy: 0.9657596361610084

Test set performance

In [24]:
# Test set
import tensorflow as tf
saver = tf.train.Saver()
BATCH_SIZE = 128
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    validation_accuracy = evaluate(X_test_norm, y_test)

    print('Test set accuracy: {:.5f}'.format(validation_accuracy))
    
INFO:tensorflow:Restoring parameters from ./lenet
Test set accuracy: 0.95305

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [25]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
from skimage import img_as_ubyte
import matplotlib.image as mpi
import os
import cv2
custom_images_raw = []
for image in sorted(os.listdir('signs')):
    img = mpi.imread(os.path.join('signs', image))
    img2 = cv2.resize(img, (32, 32))#, interpolation=cv2.INTER_CUBIC)
    img2 = img_as_ubyte(img2)
    custom_images_raw.append(img2)
custom_images_raw = np.array(custom_images_raw)
print("image type before conversion:", custom_images_raw[0].dtype)

custom_images = transform_or_load(custom_images_raw, "custom images", "custom_norm.p", func=normalize)
print("image type after conversion:", custom_images[0].dtype)
image type before conversion: uint8
Loading 'custom images' from file custom_norm.p...
  read 5 records in 0.001s
Statistics on 'custom images':
  mean: 0.0059, std dev: 0.2900
image type after conversion: float64
/usr/lib/python3/dist-packages/skimage/util/dtype.py:107: UserWarning: Possible precision loss when converting from float32 to uint8
  "%s to %s" % (dtypeobj_in, dtypeobj))
In [26]:
custom_labels = [30, 25, 1, 12, 38]
#custom_labels = [1, 12, 38, 25, 30]
show_images([x for x in range(len(custom_images))], 
            [x + 0.5 for x in custom_images], # reverse subtraction of 0.5 for prettier looking images
            custom_labels, title="the custom data set")
Showing 5 Images from the custom data set:

Predict the Sign Type for Each Image

In [27]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
import tensorflow as tf
saver = tf.train.Saver()
BATCH_SIZE = 1
    
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    for idx in range(5):
        feed_dict = {x: np.array([custom_images[idx]]), y: np.array([custom_labels[idx]]), keep_prob: 1.0}
        classification = sess.run(tf.nn.softmax(logits), feed_dict=feed_dict)
        
        #print(classification)    
        #print("highest: {}, sum: {}".format(np.max(classification), np.sum(classification)))
        print("predicted", np.argmax(classification), "vs", custom_labels[idx])
INFO:tensorflow:Restoring parameters from ./lenet
predicted 30 vs 30
predicted 25 vs 25
predicted 1 vs 1
predicted 12 vs 12
predicted 38 vs 38

Analyze Performance

In [28]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
# Test set
import tensorflow as tf
saver = tf.train.Saver()
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    validation_accuracy = evaluate(custom_images, custom_labels)

    print('Test accuracy: {:.5f}'.format(validation_accuracy))
    
INFO:tensorflow:Restoring parameters from ./lenet
Test accuracy: 1.00000

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [29]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.

### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
import tensorflow as tf
saver = tf.train.Saver()
BATCH_SIZE = 1

fig = plt.figure()
fig.clear()
fig.set_size_inches(7, 10) # use a non-square size

n_custom_images = 5
    
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    for idx in range(n_custom_images):
        # Show the image on the left
        ax = fig.add_subplot(n_custom_images, 2, (idx*2) + 1)
        ax.set_title(sign_name(custom_labels[idx]))
        ax.imshow(custom_images[idx] + 0.5) # reverse subtraction of 0.5 for prettier looking images
        ax.axis('off')
        # Show a plot of the softmax probabilities on the right
        ax = fig.add_subplot(n_custom_images, 2, (idx*2) + 2)
        ax.set_xlim([0., 1.]) # probabilities
        ax.set_ylim([0, n_custom_images])
        feed_dict = {x: np.array([custom_images[idx]]), 
                     y: np.array([custom_labels[idx]]), keep_prob: 1.0}
        classification = sess.run(tf.nn.top_k(tf.nn.softmax(logits), k=n_custom_images), feed_dict=feed_dict)
        values = classification.values[0]
        indices = classification.indices[0]
        labels = ["{} ({})".format(sign_name(x), x) for x in indices]
        ax.barh(list(range(len(values)))[::-1], values, tick_label=labels, align='center')
      
        
fig.tight_layout()
INFO:tensorflow:Restoring parameters from ./lenet

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.


Step 4 (Optional): Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [30]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")

Beware of ice/snow

In [31]:
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    outputFeatureMap([custom_images[0]], lenet.layers["conv1"])    
INFO:tensorflow:Restoring parameters from ./lenet

Speed limit (30km/h)

In [32]:
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    outputFeatureMap([custom_images[2]], lenet.layers["conv1"])
INFO:tensorflow:Restoring parameters from ./lenet

Priority road

In [33]:
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    outputFeatureMap([custom_images[3]], lenet.layers["conv1"])    
INFO:tensorflow:Restoring parameters from ./lenet
In [34]:
with tf.Session() as sess:
    saver.restore(sess, './lenet')
    outputFeatureMap([custom_images[4]], lenet.layers["conv1"])    
INFO:tensorflow:Restoring parameters from ./lenet
In [ ]: